import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cart:[],
    allChecked:false,
    totalNum:0,
    totalPrice:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const userInfo = wx.getStorageSync('userinfo')
    if(userInfo===null || userInfo===""){
      wx.navigateTo({
        url: '/pages/login/index'
      })
    }
    this.getCart();
  },
  onShow() {
    const userInfo = wx.getStorageSync('userinfo')
    if(userInfo===null || userInfo===""){
      wx.navigateTo({
        url: '/pages/login/index'
      })
    }
    this.getCart();
  },
  onHide: function() {
    this.setCart();
  },
  //当redirectTo或navigateBack的时候调用。
  onUnload: function() {
    this.setCart();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.getCart();
  },
  changeCart(cart){
    let allChecked = true;
    let totalPrice = 0;
    let totalNum = 0;
    if(cart){
      cart.forEach(v=>{
        if(v.isCheck){
          totalPrice += v.price*v.amount
          totalNum += v.amount
        }else{
          allChecked = false
        }
      })
      allChecked = cart.length!=0?allChecked:false;
      wx.setStorageSync('cart', cart)
      this.setData({
        allChecked,
        totalPrice,
        totalNum,
        cart
      })
    }
    
  },
  //获取购物车列表
  async getCart(){
    //从服务器获取购物车数据
    const userInfo = wx.getStorageSync('userinfo')
    const res = await request({ url: "shopCart/getCart", data: {userId:userInfo.id}, method: 'GET' });
    let cart = res.data;
    this.changeCart(cart);
    wx.stopPullDownRefresh();
  },
  //页面卸载或隐藏时如果购物车有数据则更新服务器购物车
  async setCart(){
    const cart = this.data.cart;
    if(cart.length===0){
      console.log("无数据")
      return;
    }
    //获取购物车并请求修改
    const userInfo = wx.getStorageSync('userinfo')
    let param = {
      userId:userInfo.id,
      carts:JSON.stringify(cart)
    }
    const result = await request({ url: "shopCart/setCart", data: param, method: 'POST' });
  },
  handleItemChange(e){
    const goodsId = e.currentTarget.dataset.id;
    let cart = this.data.cart;
    let index = cart.findIndex(v=>v.goodsId===goodsId);
    cart[index].isCheck=!cart[index].isCheck;
    this.setData({
      cart
    })
    this.changeCart(cart);
  },
  handleAllCheck(){
    let {cart,allChecked} = this.data;
    allChecked = !allChecked;
    cart.forEach(v=>v.isCheck=allChecked);

    this.changeCart(cart);
  },
  handleNumEdit(e){
    const {id,operation} = e.currentTarget.dataset;
    let {cart} = this.data;
    const index = cart.findIndex(v=>v.goodsId===id);
    if(cart[index].amount===1&&operation===-1){
      wx.showModal({
        title: '提示',
        content: '是否删除该商品？',
        success: (res)=> {
          if (res.confirm) {
            cart.splice(index,1);
            this.changeCart(cart);
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      cart[index].amount += operation;
    this.changeCart(cart);
    }
  },
  handlePay(){
    const {totalNum}=this.data;
    if(totalNum===0){
      wx.showToast({
        title: '购物车里没有商品哦',
        icon:'none'
      })
      return;
    }
    wx.redirectTo({
      url: '/pages/pay/index'
    })
  }
})